import re
import logging

class SensitiveDataFilter(logging.Filter):
    """过滤敏感信息的过滤器"""
    
    def __init__(self):
        super().__init__()
        # 定义敏感信息的正则表达式
        self.patterns = [
            (re.compile(r'password["\']?\s*[:=]\s*["\']?([^"\']+)["\']?', re.I), r'password=***'),
            (re.compile(r'card_number["\']?\s*[:=]\s*["\']?(\d{4})[\d\s]+(\d{4})["\']?', re.I), r'card_number=\1****\2'),
            # 身份证号码匹配
            (re.compile(r'(id_card|身份证)["\']?\s*[:=]\s*["\']?(\d{6})[\d\s]+(\d{4})["\']?', re.I), r'\1=\2******\3'),
            # 手机号码匹配
            (re.compile(r'(phone|mobile|手机)["\']?\s*[:=]\s*["\']?(\d{3})[\d\s]+(\d{4})["\']?', re.I), r'\1=\2*****\3'),
            # 邮箱地址匹配
            (re.compile(r'(email|邮箱)["\']?\s*[:=]\s*["\']?([^@\s]+)@([^\s]+)["\']?', re.I), r'\1=\2***@\3'),
            # API密钥匹配
            (re.compile(r'(api_key|apikey|token)["\']?\s*[:=]\s*["\']?([a-zA-Z0-9]{4})([a-zA-Z0-9]+)["\']?', re.I), r'\1=\2***'),
        ]
    
    def filter(self, record):
        if isinstance(record.msg, str):
            msg = record.msg
            for pattern, repl in self.patterns:
                msg = pattern.sub(repl, msg)
            record.msg = msg
        return True